package com.ruoyi.web.controller.glzz;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.WriteApiBlocking;
import com.influxdb.client.domain.WritePrecision;
import com.influxdb.client.write.Point;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.web.controller.dao.GpsDao;
import com.ruoyi.web.controller.dao.TShipDeviceSubject;
import com.ruoyi.web.controller.dao.ValueImportExcel;
import com.ruoyi.web.controller.glzz.fileRevertUtil.ReturnResponse;
import com.ruoyi.web.service.glzz.TShipDeviceSubjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * glzz菜单Controller
 *
 * @author sci
 * @date 2024-05-13
 */
@SuppressWarnings({"DefaultAnnotationParam", "PointlessBooleanExpression"})
@Api(value = "glzz菜单", tags = {"工具接口"})
@RestController
@RequestMapping("/system/utilsApi")
@Slf4j
public class TGlzzUtilsApiController extends BaseController {
    @Autowired
    TShipDeviceSubjectService tShipDeviceSubjectService;

    /**
     * 读取目标文件夹下文件并全部转为pinyin
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "directoryPath", value = "文件地址", required = false, paramType = "query"),
    })
    @ApiOperation("读取目标文件夹下文件并全部转为pinyin")
    @PostMapping("/changeNameToPinyin")
    public AjaxResult changeNameToPinyin(

    ) {

//      读取目标文件夹下文件并全部转为应为
        String directoryPath = "D:\\znzzIcons";
        renameIconsInDirectory(directoryPath);
        return success();
    }

    public static void renameIconsInDirectory(String directoryPath) {
        File directory = new File(directoryPath);
        if (!directory.exists() || !directory.isDirectory()) {
            System.out.println("Directory does not exist or is not a directory: " + directoryPath);
            return;
        }

        File[] files = directory.listFiles((dir, name) -> name.endsWith(".png"));
        if (files != null) {
            for (File file : files) {
                String originalName = file.getName();
                String newName = renameIcon(originalName);

                File newFile = new File(directory, newName);
                try {
                    Files.move(file.toPath(), newFile.toPath());
                    System.out.println("Renamed: " + originalName + " to " + newName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static String renameIcon(String originalText) {
        StringBuilder pinyinBuilder = new StringBuilder();
        char[] chars = originalText.toCharArray();
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        for (char c : chars) {
            if (Character.toString(c).matches("[\\u4e00-\\u9fa5]+")) { // 检查是否为中文字符
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null) {
                        pinyinBuilder.append(pinyinArray[0]);
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                // 非中文字符直接添加到拼音字符串中（如果需要的话）
                // 这里可以根据你的需求来处理非中文字符
                pinyinBuilder.append(c);
            }
        }

        return pinyinBuilder.toString();
    }

    @ApiOperation("gps绑定设备")
    @PostMapping("linkDevice")
    public AjaxResult linkDevice(@RequestBody GpsDao gpsDao) {
        JSONObject loginInfo = getLoginInfo();
        String mds = loginInfo.getString("mds");
        String login_id = loginInfo.getString("id");
        String linkResult = null;
        try {
            linkResult = sendGet("http://apitest.18gps.net//GetDateServices.asmx/GetDate?method=ActiveAndAddDevice&login_id=" + login_id + "&mds=" + mds + "&FullName=H25685&Macid=" + gpsDao.getMacId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return success(linkResult);
    }

    @ApiOperation("查询全部的gps设别列表")
    @GetMapping("getDeviceList")
    public AjaxResult getDeviceList() {
        JSONObject loginInfo = getLoginInfo();
        String mds = loginInfo.getString("mds");
        String deviceList = null;
        try {
            deviceList = sendGet("http://apitest.18gps.net//GetDateServices.asmx/GetDate?method=getDeviceList&mds=" + mds);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        JSONObject deviceObjectList = JSONObject.parseObject(deviceList);
        String string = deviceObjectList.getString("rows");
        JSONArray deviceArrayList = JSONArray.parseArray(string);
        return success(deviceArrayList);
    }

    @ApiOperation("查询单个设备的最新具体位置")
    @GetMapping("getDeviceLastPosition")
    public AjaxResult getDeviceLastPosition(@RequestParam(value = "deviceId", required = true) String deviceId) {
        JSONObject loginInfo = getLoginInfo();
        String mds = loginInfo.getString("mds");
        String deviceObjectStr = null;
        try {
            deviceObjectStr = sendGet("http://apitest.18gps.net/GetDateServices.asmx/GetDate?mapType=BAIDU&mds=" + mds + "&method=getUserAndGpsInfoByIDsUtc&option=cn&user_id=" + deviceId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        JSONObject jsonObject = JSONObject.parseObject(deviceObjectStr);
        String records = jsonObject.getString("records");
        return success(records);
    }

    @ApiOperation("设备绑定企业")
    @PostMapping("lineDevieForSubjectApi")
    public AjaxResult lineDevieForSubjectApi(@RequestBody GpsDao gpsDao) {
        String subjectCode = gpsDao.getSubjectCode();
        String imei = gpsDao.getImei();
        String deviceId = gpsDao.getDeviceId();
        System.out.println(1111);
        TShipDeviceSubject tShipDeviceSubject = new TShipDeviceSubject();
        tShipDeviceSubject.setSubjectCode(subjectCode);
        tShipDeviceSubject.setId(IdUtils.fastUUID());
        tShipDeviceSubject.setImei(imei);
        tShipDeviceSubject.setDeviceId(deviceId);
        boolean save = tShipDeviceSubjectService.save(tShipDeviceSubject);
        return AjaxResult.success("保存成功");
    }

    public JSONObject getLoginInfo() {
        String s = null;
        try {
            s = sendGet("http://apitest.18gps.net/GetDateServices.asmx/loginSystem?LoginName=鑫逸号&LoginPassword=123456&LoginType=ENTERPRISE&language=cn&ISMD5=0&timeZone=+08&apply=APP&loginUrl=http://vipopenapi.18gps.net/");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        JSONObject jsonObject = JSONObject.parseObject(s);
        return jsonObject;
    }

    public static String sendGet(String url) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 可选，设置请求方法: GET
        con.setRequestMethod("GET");

        // 可选，设置请求的超时时间
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);

        // 发送GET请求
        int responseCode = con.getResponseCode();
        System.out.println("GET Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 释放连接
        con.disconnect();

        return response.toString();
    }



    @ApiOperation("导入数据传入到时序数据库")
    @PostMapping("exportValueExcelToDatabase")
    public AjaxResult exportValueExcelToDatabase(@RequestBody GpsDao gpsDao) {
        String subjectCode = gpsDao.getSubjectCode();
        String imei = gpsDao.getImei();
        String deviceId = gpsDao.getDeviceId();
        System.out.println(1111);
        TShipDeviceSubject tShipDeviceSubject = new TShipDeviceSubject();
        tShipDeviceSubject.setSubjectCode(subjectCode);
        tShipDeviceSubject.setId(IdUtils.fastUUID());
        tShipDeviceSubject.setImei(imei);
        tShipDeviceSubject.setDeviceId(deviceId);
        boolean save = tShipDeviceSubjectService.save(tShipDeviceSubject);
        return AjaxResult.success("保存成功");
    }

}
